<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>形成三的最大倍数</title>
</head>
<body>
  <script>
    function fn(digits) {
      let sum = digits.reduce((p, v) => p + v)
      if (sum === 0 && sum.length !== 0) {
        return "0"
      } else if (sum % 3 === 0) {
        return digits.sort((a, b) => b - a).join("")
      }
      let map_1 = digits.filter(item => item % 3 === 0).sort((a, b) => b - a)
      let map_2 = digits.filter(item => item % 3 === 1).sort((a, b) => b - a)
      let map_3 = digits.filter(item => item % 3 === 2).sort((a, b) => b - a)
      if (sum % 3 === 1) {
        if (map_2.length > 0) {
          map_2.pop()
          return [...map_1, ...map_2, ...map_3].sort((a, b) => b - a).join("")
        } else if (map_3.length > 1) {
          map_3.pop()
          map_3.pop()
          return [...map_1, ...map_2, ...map_3].sort((a, b) => b - a).join("")
        }
      } else {
        if (map_3.length > 0) {
          map_3.pop()
          return [...map_1, ...map_2, ...map_3].sort((a, b) => b - a).join("")
        } else if (map_2.length > 1) {
          map_2.pop()
          map_2.pop()
          return [...map_1, ...map_2, ...map_3].sort((a, b) => b - a).join("")
        }
      }
    }
    console.log(fn([8, 1, 9]))
  </script>
</body>
</html>